package com.mouse.hxsj.util;

import javax.swing.*;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class ViewSet {
    public static void textField(JTextField jTextField, Object o) {
        if (o == null) return;
        jTextField.setText(o.toString());
    }

    public static void comboBox(JComboBox jComboBox, int index) {
        if (jComboBox.getItemCount() > index) jComboBox.setSelectedIndex(index);

    }

    public static void comboBox(JComboBox jComboBox, Object value, String key) {
        int itemCount = jComboBox.getItemCount();
        for (int i = 0; i < itemCount; i++) {
            Object item = jComboBox.getItemAt(i);
            if (item == null) continue;
            if (item instanceof String) {
                if (value != null && value.toString().equals(item)) {
                    jComboBox.setSelectedIndex(i);
                    return;
                }
            } else {
                Class<?> aClass = item.getClass();
                List<Field> fieldList = Arrays.stream(aClass.getDeclaredFields()).filter(field -> field.getName().equals(key)).collect(Collectors.toList());
                if (fieldList.size() == 0) return;
                Field field = fieldList.get(0);
                field.setAccessible(true);
                Object o = null;
                try {
                    o = field.get(item);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                if (o != null && o.equals(value)) {
                    jComboBox.setSelectedIndex(i);
                    return;
                } else if (o == null) {
                    if (value == null) {
                        jComboBox.setSelectedIndex(i);
                        return;
                    }
                }
            }
        }
    }
}
